﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using ImageTools.IO.Gif;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using MyDeeWeibo.Classes;
using Coding4Fun.Phone.Controls;

namespace MyDeeWeibo.PageViews
{
    public partial class UserProfile : PhoneApplicationPage
    {
        #region UserTimelineListProperty
        public static readonly DependencyProperty UserTimelineListProperty =
            DependencyProperty.Register(
            "UserTimelineList",
            typeof(ObservableCollection<WStatus>),
            typeof(UserProfile),
            new PropertyMetadata((ObservableCollection<WStatus>)null));

        public ObservableCollection<WStatus> UserTimelineList
        {
            get { return (ObservableCollection<WStatus>)GetValue(UserTimelineListProperty); }
            set { SetValue(UserTimelineListProperty, value); }
        }
        #endregion

        #region UserProfileShowProperty
        public static readonly DependencyProperty UserProfileShowProperty =
            DependencyProperty.Register(
            "UserProfileShow",
            typeof(ObservableCollection<User>),
            typeof(UserProfile),
            new PropertyMetadata((ObservableCollection<User>)null));

        public ObservableCollection<User> UserProfileShow
        {
            get { return (ObservableCollection<User>)GetValue(UserProfileShowProperty); }
            set { SetValue(UserProfileShowProperty, value); }
        }
        #endregion

        #region FriendshipFollowingProperty
        public static readonly DependencyProperty FriendshipFollowingProperty =
            DependencyProperty.Register(
            "FriendshipFollowing",
            typeof(ObservableCollection<User>),
            typeof(UserProfile),
            new PropertyMetadata((ObservableCollection<User>)null));

        public ObservableCollection<User> FriendshipFollowing
        {
            get { return (ObservableCollection<User>)GetValue(FriendshipFollowingProperty); }
            set { SetValue(FriendshipFollowingProperty, value); }
        }
        #endregion

        #region FriendshipFollowerProperty
        public static readonly DependencyProperty FriendshipFollowerProperty =
            DependencyProperty.Register(
            "FriendshipFollower",
            typeof(ObservableCollection<User>),
            typeof(UserProfile),
            new PropertyMetadata((ObservableCollection<User>)null));

        public ObservableCollection<User> FriendshipFollower
        {
            get { return (ObservableCollection<User>)GetValue(FriendshipFollowerProperty); }
            set { SetValue(FriendshipFollowerProperty, value); }
        }
        #endregion

        #region ProgressIndicatorIsVisibleProperty
        public static readonly DependencyProperty ProgressIndicatorIsVisibleProperty =
            DependencyProperty.Register("ProgressIndicatorIsVisible",
            typeof(bool),
            typeof(UserProfile),
            new PropertyMetadata(false));

        public bool ProgressIndicatorIsVisible
        {
            get { return (bool)GetValue(ProgressIndicatorIsVisibleProperty); }
            set { SetValue(ProgressIndicatorIsVisibleProperty, value); }
        }
        #endregion

        public User ProfileShow;
        public WStatus sStatusShow; //传递微博id
        public User sUserShow; //传递用户id

        //从发送页面返回时判断
        public bool sendSuccess;

        public ObservableCollection<User> DataCollection { get; set; }
        public ObservableCollection<User> BuildCollection()
        {
            DataCollection = new ObservableCollection<User>();
            DataCollection.Add(ProfileShow);
            UserProfileShow = DataCollection;
            return UserProfileShow;
        }

        private DeeCmdBase cmdBase;
        private DeeNetEngine netEngine;

        public UserProfile()
        {
            InitializeComponent();
        }

        private void RefreshUserTimeline()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdUserTimeline
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                userId = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.USER_TIMELINE, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatuses utimeliststatuses = null;
                        try
                        {
                            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(WStatuses));
                            utimeliststatuses = ser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            UserTimelineList = new ObservableCollection<WStatus>(utimeliststatuses.statuses);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshUserProfile()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdUserTimeline
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                userId = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.USER_PROFILE, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        try
                        {
                            DataContractJsonSerializer pser = new DataContractJsonSerializer(typeof(User));
                            ProfileShow = pser.ReadObject(response.stream) as User;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            BuildCollection();
                            if (ProfileShow.following)
                            {
                                ApplicationBarMenuItem unFollowButton = new ApplicationBarMenuItem();
                                unFollowButton.Text = "取消关注";
                                ApplicationBar.MenuItems.Add(unFollowButton);
                                unFollowButton.Click += new EventHandler(unFollowButton_Click);
                            }
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void FriendshipCreate()
        {

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdFriendShip
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                _userId = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.FRIENDSHIP_CREATE, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    //Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            RefreshUserProfile(); //刷新关注button
                            var messagePrompt = new MessagePrompt
                            {
                                Title = "提示",
                                Message = "关注成功",
                            };
                            messagePrompt.Show();
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void FriendshipDestroy()
        {

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdFriendShip
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                _userId = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.FRIENDSHIP_DESTROY, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    //Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        try
                        {
                            DataContractJsonSerializer pser = new DataContractJsonSerializer(typeof(User));
                            ProfileShow = pser.ReadObject(response.stream) as User;
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            BuildCollection(); //刷新关注button
                            var messagePrompt = new MessagePrompt
                            {
                                Title = "提示",
                                Message = "已取消关注",
                            };
                            messagePrompt.Show();
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshFollowing()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdFriendShip
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30",
                user_id = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.FRIENDSHIP_FOLLOWING, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatuses userfollowings = null;
                        try
                        {
                            DataContractJsonSerializer cmser = new DataContractJsonSerializer(typeof(WStatuses));
                            userfollowings = cmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            FriendshipFollowing = new ObservableCollection<User>(userfollowings.users);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void RefreshFollower()
        {
            ProgressIndicatorIsVisible = true;

            // Define a new net engine
            netEngine = new DeeNetEngine();

            // Define a new command base
            cmdBase = new cmdFriendShip
            {
                acessToken = App.AccessToken,
                //acessTokenSecret = App.AccessTokenSecret,
                count = "30",
                user_id = App.UserID
            };


            // Request server, the last parameter is set as default (".json")
            netEngine.RequestCmd(DeeRequestType.FRIENDSHIP_FOLLOWER, cmdBase,
                // Requeset callback
                delegate(DeeRequestType requestType, DeeResponse response)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => ProgressIndicatorIsVisible = false);
                    if (response.errCode == DeeErrCode.SUCCESS)
                    {
                        WStatuses userfollowers = null;
                        try
                        {
                            DataContractJsonSerializer cmser = new DataContractJsonSerializer(typeof(WStatuses));
                            userfollowers = cmser.ReadObject(response.stream) as WStatuses;
                        }
                        catch (Exception)
                        {
                            throw;
                        }


                        // Use dispatcher invoke when you want to use UI thread to do things in callback delegate
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            FriendshipFollower = new ObservableCollection<User>(userfollowers.users);
                        });
                    }
                    else
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() => MessageBox.Show(response.content, response.errCode.ToString(), MessageBoxButton.OK));
                    }
                });
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            SystemTray.ProgressIndicator = new ProgressIndicator();
            SystemTray.ProgressIndicator.Text = "数据传输中";

            Binding bindingData;
            bindingData = new Binding("ProgressIndicatorIsVisible");
            bindingData.Source = this;
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsVisibleProperty, bindingData);
            BindingOperations.SetBinding(SystemTray.ProgressIndicator, ProgressIndicator.IsIndeterminateProperty, bindingData);

            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
        }

        private void ProfilePivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (ProfilePivot.SelectedIndex)
            {
                case 0:
                    {
                        RefreshUserProfile();
                    }
                    break;
                case 1:
                    {
                        RefreshUserTimeline();
                    }
                    break;
                case 2:
                    {
                        RefreshFollowing();
                    }
                    break;
                case 3:
                    {
                        RefreshFollower();
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        private void refreshIconButton_Click(object sender, EventArgs e)
        {
            switch (ProfilePivot.SelectedIndex)
            {
                case 0:
                    {
                        RefreshUserProfile();
                    }
                    break;
                case 1:
                    {
                        RefreshUserTimeline();
                    }
                    break;
                case 2:
                    {
                        RefreshFollowing();
                    }
                    break;
                case 3:
                    {
                        RefreshFollower();
                    }
                    break;
                default:
                    {

                    }
                    break;
            }
        }

        void SendCompleted(object sender, SendCompletedEventArgs e)
        {
            if (e.IsSendSuccess)
                sendSuccess = true;
            else
                MessageBox.Show(e.Response, e.ErrorCode.ToString(), MessageBoxButton.OK);
        }

        private void UserSettings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/PageViews/UserSettings.xaml", UriKind.Relative));
        }

        private void userWeibo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sStatusShow = (sender as ListBox).SelectedItem as WStatus;
            if (sStatusShow != null)
            {
                NavigationService.Navigate(new Uri("/PageViews/WeiboContent.xaml", UriKind.Relative));
            }
        }

        //data to another xaml
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            WeiboContent StatusShow = e.Content as WeiboContent;
            if (StatusShow != null)
            {
                StatusShow.StatusResults = sStatusShow;
                userWeibo.SelectedItem = null;
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (sendSuccess)
            {
                var messagePrompt = new MessagePrompt
                {
                    Title = "提示",
                    Message = "发送成功",
                };
                messagePrompt.Show();
                sendSuccess = false;
            }
        }

        private void atUserButton_Click(object sender, EventArgs e)
        {
            DeeShare sdkSend = new DeeShare();
            sdkSend.AccessToken = App.AccessToken;
            sdkSend.Message = "@" + ProfileShow.screen_name + " ";
            sdkSend.Completed = SendCompleted;
            sdkSend.Show();
        }

        private void followings_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sUserShow = (sender as ListBox).SelectedItem as User;
            if (sUserShow != null)
            {
                App.UserID = sUserShow.id;
                UserProfileShow = null;
                UserTimelineList = null;
                FriendshipFollowing = null;
                FriendshipFollower = null;
                ProfilePivot.SelectedIndex = 0;
            }
        }

        private void followers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            sUserShow = (sender as ListBox).SelectedItem as User;
            if (sUserShow != null)
            {
                App.UserID = sUserShow.id;
                UserProfileShow = null;
                UserTimelineList = null;
                FriendshipFollowing = null;
                FriendshipFollower = null;
                ProfilePivot.SelectedIndex = 0;
            }
        }

        private void followButton_Click(object sender, RoutedEventArgs e)
        {
            FriendshipCreate();
        }

        private void unFollowButton_Click(object sender, EventArgs e)
        {
            FriendshipDestroy();
        }

        private void ListBox_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {

        }

    }
}